<?php
namespace Mobile\Controller;
use Think\Controller;

//前台首页模块
class TourismController extends Controller{
	//旅游分类
	public function tourism_pagelist(){
		if(empty($_GET['pageid'])){
			$goods_class = M('goods_class');
			$where['type'] = 2;
			$where['fid'] = 0;
			$resone = $goods_class->where($where)->select();
			$this->assign('resone',$resone);
			/* $fid = 16;
				$find = $goods_class->where('fid='.$fid)->order('id desc')->select();
				foreach($find as $n=>$val){
				$find[$n]['vo'] = M('goods')->where('class_id='.$val['id'])->select();
				}
			$this->assign('find',$find); */
			$this->display();
		}else{
			$fid = $_GET['pageid'];
			$goods_class = M('goods_class');
			$where['type'] = 2;
			$where['fid'] = $fid;
			$findone = $goods_class->where($where)->select();
			/* foreach($findone as $n=>$val){
			 $findone[$n]['vo'] = M('goods_class')->where('fid='.$val['id'])->select();
			} */
			/* foreach($findone as $n=>$val){
			 $findone[$n]['vo'] = M('goods')->where('class_id='.$val['id'])->limit('4')->select();
			} */
			$this->ajaxReturn( json_encode($findone));
		}
	}
	
	//旅游商品列表
	public function tourism_tourismlist(){
		if(!empty($_GET['fid'])){
			$where['class_fid'] = $_GET['fid'];
		}else{
			$where['class_id'] = $_GET['id'];
		}
		$goods = M('goods');		
		$where['shangjia'] = 1;
		$find = $goods->where($where)->order('sort_num')->select();

		$this->assign('finds',$find);
		$this->display();
	}
	//获取到用户自己的id供分享网址使用
	public function _before_tourism_tourism(){
		//exit;
		$id=I('id');//商品id
		//用户id
		if(session('user_id')!=null){
			$user_id=session('user_id');
		}elseif(cookie('user_id')!=null){
			$user_id=cookie('user_id');
		}elseif(cookie('userid')!=null){
			$user_id=cookie('userid');
		}else{
			$user_id=10000000;
		}
		if(!I('get.pid')){
			$this->redirect('Tourism/tourism_tourism',array('id'=>$id,'pid'=>$user_id));
		 }
		
	}
	//旅游商品页面
	public function tourism_tourism(){
		$goods = M('goods');
		$pid = I('get.pid');
		cookie('mytuijianren',$pid,86400);
		$where['id'] = $_GET['id'];
		$resone = $goods->where($where)->find();

		$chufa_taocan = unserialize($resone['chufa_taocan']);
//dump($chufa_taocan);
$now_date = date('Y-m-d',time());

foreach($chufa_taocan as $kk=>$vv){
	if($vv['chufa_date'] < $now_date){
		unset($chufa_taocan[$kk]);
	}	
}
//dump($chufa_taocan);
		$this->assign('chufa_taocan',$chufa_taocan);


		$pic = unserialize($resone['pic_tuji']);
		$this->assign('pic',$pic);
		$this->assign('resone',$resone);

		$member = M('member','vip_');
		$where_m['id'] = $_COOKIE['user_id'];
		$res_member = $member->where($where_m)->find();
		$this->assign('res_member',$res_member);

		$m = M('goods_shoucang');
		$where_sc['user_id'] = $_COOKIE['user_id'];
		$where_sc['goods_id'] = $_GET['id'];
		$result_sc = $m->where($where_sc)->find();

		$this->assign('result_sc',$result_sc);

		$this->display();
	}


	//旅游-结算页
	public function tourism_count(){

		//dump($_POST);

		if(empty($_COOKIE['userid'])){
			$this->redirect('User/login');
		}

		$_POST['chufa_date'] = substr($_POST['chufa_date'],0,10);

		if(empty($_POST['chufa_date'])){
			$this->error('出发日期不能为空');
		}
		//获得传递过来的数据 并且做相关的处理
		//判断是否是立即付款
		//判断post过来的数据是否存在
/*dump($_POST['price_new']);
dump($_POST['goods_num']);
dump($_POST['price_new'] * $_POST['goods_num']);*/
		$goods_data[] = $_POST;
		$_SESSION['price_sum'] = $_POST['chufa_price'] * $_POST['goods_num'] + $_POST['chufa_price_et'] * $_POST['goods_num_et'];
		$_SESSION['goods_data'] = $goods_data;	//选中的商品数据临时存储在session中

		$this->assign('price_sum',$_SESSION['price_sum']);	//合计金额
		$this->assign('goods_data',$_SESSION['goods_data']);	//选择的商品

		//判断是否是微信浏览器
		if(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ){//是
			$weixin['isok'] = 1;
		}else{
			$weixin['isok'] = 2;
		}

		$this->assign('order_type',$_POST['type']);		
		//dump(session());exit;
		$this->assign('weixin',$weixin);
		//选择地址
		$userid = $_COOKIE['userid'];
		/**查询积分账户余额**/
		$my=M('user')->where(array('id'=>$userid))->find();
		$this->assign('jfa',$my['add_jf_limit']);
		$this->assign('jfb',$my['add_jf_currency']);
		/**查询用户等级**/
		$grade=M('member','vip_')->where(array('id'=>$userid))->getField('grade_name');
		$this->assign('grade',$grade);
		$where['user_id'] = $userid;
		$this->assign('weixin',$weixin);
		$find_address = M('user_address')->where($where)->find();

		$this->assign('find',$find_address);
		$this->display();

	}

	
	//旅游商品详情
	public function tourism_detail(){
		$where['id'] = $_GET['id'];
		$goods = M('goods');
		$resone = $goods->where($where)->find();
		//dump($resone);
		$this->assign('resone',$resone);
		$this->display();
	}

	//旅游商品详情
	public function tourism_detail_m(){
		$where['id'] = $_GET['id'];
		$goods = M('goods');
		$resone = $goods->where($where)->find();
		//dump($resone);
		$this->assign('resone',$resone);
		$this->display();
	}
	
	//商品评价
	public function tourism_evaluate(){
		$id = $_GET['id'];
		$goods = M('goods');
		$resone = $goods->where('id='.$id)->find();
		$this->assign('resone',$resone);

		$this->display();
	}
	
	//添加旅游足迹
	public function add_footprint(){
		if(IS_POST){
			$info = M('foot_print');
			$_POST['uid'] = $_COOKIE['userid'];
			$_POST['gid'] = I('gid');
			$_POST['goods_pic'] = I('goods_pic');
			$_POST['goods_name'] = I('goods_name');
			$_POST['goods_price'] = I('goods_price');
			$_POST['type'] = I('type');
			$_POST['create_time'] = time();
			$result = $info->where(array('uid'=>$_POST[uid],'gid'=>$_POST[gid]))->select();
			if(!empty($_COOKIE['userid'])){
				if(!$result){
					$info->add($_POST);
				}else{
					$info->where(array('uid'=>$_POST[uid],'gid'=>$_POST[gid]))->save($_POST);
				}
			}
		}
	}
	
	
	
	/*
	 * 旅游提交订单
	 */
	public function place_order(){

		$goods_orders = M('Goods_orders');
		$user = M('User');
		$user_id = cookie('userid');
		if($user_id ==''){
			$this->redirect('Mobile/User/login');
		}
		$jfb=$user->where(array('id'=>$user_id ))->getField('add_jf_currency');
		if(isset($_POST['jfa']) && $_POST['jfa']!=0){
			$this->error('旅游产品只能消费B账户积分');
		}
		$orders_num = time().sprintf("%06s",$_COOKIE['userid']);
		//判断用户类型
		$grade=M('member','vip_')->where(array('id'=>$user_id ))->getField('grade_name');
		if($grade=='合伙人'){
			if(I('post.jfa')!=0 || I('post.jfb')!=0 ){
				$this->error('合伙人不能使用积分购买旅游产品');
			}
		}
		if(I('post.jfb')<0){
			$this->error('积分不能为负数');
		}
		if(I('post.jfb')>$jfb){
			$this->error('积分账户不足');
		}
		
		$res = $user->field('username')->where('id = '.$user_id)->find();


		$_data['use_jf_currency']=I('post.jfb');//保存使用的积分
		$_data['use_jf_limit']=0;
		$_data['orders_num'] = $orders_num;
		$_data['order_type'] = 1;
		$_data['user_id'] = $user_id;
		$_data['price_sum'] = $_POST['price_sum']-$_POST['jfb'];
		$_data['fanli_jifen'] = $_POST['fanli_jifen'][0] * $_POST['goods_num'][0];
		//exit;
		$_data['realname'] = $res['username'];
		$_data['create_time'] = time();
		$_data['realname'] = $_POST['realname'];
		$_data['mobile'] = $_POST['mobile'];
		$_data['user_address'] = $_POST['user_address'];

//exit;

		//将相关信息添加到订单表中
		$goods_orders->add($_data);

		
		$goods_orders_id = $goods_orders->getLastInsID();
		$goods_orders_record = M('Goods_orders_record');
		//这个位置旅游是1个 后期有可能要修改
		if(empty($_POST['chufa_date'])){
			$this->error('请选择出发日期');
		}
		$data_record = array(
			'goods_orders_id'=>$goods_orders_id,
			'goods_id'=>$_POST['goods_id'][0],
			'goods_num'=>$_POST['goods_num'][0],
			'user_id' =>$user_id,
			'pic_url'=>$_POST['pic_url'][0],
			'goods_title'=>$_POST['goods_title'][0],
			'chufa_address'=>$_POST['chufa_address'][0],
			'chufa_date'=>$_POST['chufa_date'][0],
			'chufa_price'=>$_POST['chufa_price'][0],
			'fanli_jifen'=>$_POST['fanli_jifen'][0],
			'chufa_price_et'=>$_POST['chufa_price_et'][0],
			'goods_num_et'=>$_POST['goods_num_et'][0]			
		);

		$info = $goods_orders_record->add($data_record);


		

		//这个位置跳到微信
		if($info){
			/*session('orders_num',$orders_num);
			$this->redirect('Mobile/Wxpay/new_pay');*/
			$user_agent = $_SERVER['HTTP_USER_AGENT'];
			if (strpos($user_agent, 'MicroMessenger') === false) {
				// 非微信浏览器禁止浏览
				$this->redirect('Mobile/Tourism/mobile_pay_money',array('orders_num'=>$orders_num));

			} else {
				// 微信浏览器，允许访问
				session('orders_num',$orders_num);
				$this->redirect('Mobile/Wxpay/new_pay');
			}


		}

	}
	
	/******************************************微信支付开始***********************************************/
	
	
	
	
	
	
	
	/******************************************微信支付结束***********************************************/
	
	
	
	/*******************************************支付宝手机支付开始***********************************************/
	/*
	*支付宝支付
	 * 支付金额
	 */

	public function mobile_pay_money(){
		require_once("./alipaymobile/alipay.config.php");
		require_once("./alipaymobile/lib/alipay_submit.class.php");

		/**************************请求参数**************************/
		//商户订单号，商户网站订单系统中唯一订单号，必填
		$out_trade_no = I('get.orders_num');


		/*****************获取自己数据库里面的值***********************/
		$info_a = strpos($out_trade_no,'u');
		if($info_a==1){

			$user_huifei = M('User_huifei');

			$res = $user_huifei->field('hf_money')->where(array(
				'orders_num'=>$out_trade_no
			))->find();

			$total_fee = $res['hf_money'];

		}elseif($info_a==2){

			$account = M('Account');
			$res = $account->field('quota')->where(array(
				'orders_num'=>$out_trade_no
			))->find();
			$total_fee = $res['quota'];

		}else{
			$res = M('Goods_orders')->field('price_sum')->where(array(
				'orders_num'=>$out_trade_no
			))->find();
			//echo M('Goods_orders')->getLastSql();
			$total_fee = $res['price_sum'];
			//dump($total_fee);

		}

		/***********************************goods_orders******/



		//订单名称，必填
		$subject = I('get.orders_num');

		//付款金额，必填
	
		//收银台页面上，商品展示的超链接，必填
		/*$show_url = 'http://www.zzumall.com/index.php/Mobile/Order/order_list.html';*/

		$info_a = strpos($out_trade_no,'u');
		if($info_a==1){
			//会员入会充钱
			$show_url = 'http://www.zzumall.com/index.php/Mobile/Mycenter/person_identity.html';
		}elseif($info_a==2){
			//会员余额充钱
			$show_url = 'http://www.zzumall.com/index.php/Mobile/Mycenter/person_balance.html';
		}else{
			//收银台页面上，商品展示的超链接，必填
			$show_url = 'http://www.zzumall.com/index.php/Mobile/Order/order_list.html';
		}



		//商品描述，可空
		$body = '';
		/************************************************************/

//构造要请求的参数数组，无需改动
		$parameter = array(
			"service"       => $alipay_config['service'],
			"partner"       => $alipay_config['partner'],
			"seller_id"  => $alipay_config['seller_id'],
			"payment_type"	=> $alipay_config['payment_type'],
			"notify_url"	=> $alipay_config['notify_url'],
			"return_url"	=> $alipay_config['return_url'],
			"_input_charset"	=> trim(strtolower($alipay_config['input_charset'])),
			"out_trade_no"	=> $out_trade_no,
			"subject"	=> $subject,
			"total_fee"	=> $total_fee,
			"show_url"	=> $show_url,
			//"app_pay"	=> "Y",//启用此参数能唤起钱包APP支付宝
			"body"	=> $body,
			//其他业务参数根据在线开发文档，添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.2Z6TSk&treeId=60&articleId=103693&docType=1
			//如"参数名"	=> "参数值"   注：上一个参数末尾需要“,”逗号。

		);
		
		//dump($parameter);
		//die;
//建立请求
		$alipaySubmit = new \AlipaySubmit($alipay_config);
		$html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认");
		echo $html_text;
		
		
		
	}

	/*
	 * 异步通知
	 */
	public function mobile_response(){
		require_once("./alipaymobile/alipay.config.php");
		require_once("./alipaymobile/lib/alipay_notify.class.php");

//计算得出通知验证结果
		$alipayNotify = new \AlipayNotify($alipay_config);
		$verify_result = $alipayNotify->verifyNotify();

		if($verify_result) {//验证成功
			/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
			//请在这里加上商户的业务逻辑程序代


			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——

			//获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表

			//商户订单号

			$out_trade_no = $_POST['out_trade_no'];

			//支付宝交易号

			$trade_no = $_POST['trade_no'];

			//交易状态
			$trade_status = $_POST['trade_status'];


			if($_POST['trade_status'] == 'TRADE_FINISHED') {


			}
			else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
				/*$data = array();
				$data['pay_status'] = 1;
				$data['pay_time'] = time();
				M('Goods_orders')->where('orders_num='.$out_trade_no)->save($data);*/

				$orders_num =$out_trade_no;
				$info_a = strpos($orders_num,'u');
				if($info_a==1){
					$data = array();
					$data['pay_status'] =1;
					$data['pay_time'] = time();
					$user_huifei = M('User_huifei');
					$user_huifei->where(array('orders_num'=>$orders_num))->save($data);
					$res = $user_huifei->field('user_id,hf_money')->where(array(
						'orders_num'=>$orders_num
					))->find();
					$user_id = $res['user_id'];
					$huifei_sum = $res['hf_money'];
					
					/************/
					$admin=M('admin','vip_');
					$user=M('user');
					$my=$user->where(array('id'=>$user_id))->find();
					$arr['account']=$my['mobile'];
					$arr['password']=$my['password'];
					$arr['create_time']=NOW_TIME;
					$arr['status']=1;
					$admin_id=$admin->add($arr);
					$auth_group_access=M('auth_group_access','vip_');
					$auth_group_access->add(array('uid'=>$admin_id,'group_id'=>51));
					$user->where(array('id'=>$user_id))->save(array('admin_id'=>$admin_id));
					$map = array();
					$year=date('Y',NOW_TIME);
					$month=date('m',NOW_TIME);
					if($res['hf_money']==365){
						$map['grade_name'] ='会员';
						R('Award/vipLogic',array($user_id,$year,$month));
						$map['vip_end'] =NOW_TIME-0+31536000;
					}else if($res['hf_money']==30000){
						R('Award/sVipLogic',array($user_id,array($year,$month)));
						$map['grade_name'] ='合伙人';
					}
					$map['admin_id'] =$admin_id;
					$map['status'] =1;
					$m = M('member','vip_');
					$m->where(array('user_id'=>$user_id))->save($map);
					
					/*************/


					M('User')->where('id='.$user_id)->setInc('huifei_sum',$huifei_sum);
				}elseif($info_a==2){
					$data = array();
					$data['pay_status'] =1;
					$data['pay_time'] = time();
					$account = M('Account');
					$account->where(array('orders_num'=>$orders_num))->save($data);
					$res = $account->field('user_id,quota')->where(array(
						'orders_num'=>$orders_num
					))->find();
					$user_id = $res['user_id'];
					$account_balance = $res['quota'];
					M('User')->where('id='.$user_id)->setInc('account_balance',$account_balance);
				}else{
					$data = array();
					$data['pay_status'] = 1;
					$data['pay_time'] = time();
					M('Goods_orders')->where(array(
						'orders_num'=>$orders_num
					))->save($data);
				}






			}

			//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

			echo "success";		//请不要修改或删除

			}
		else {
			//验证失败
			echo "fail";

			//调试用，写文本函数记录程序运行情况是否正常
			//logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
		}
	}
	/*
	 *支付成功
	 *
	 */
	public function mobile_success(){
		$this->display();
	}
	
	/*******************************************支付宝手机支付结束***********************************************/
	
	
	
	
	
	
}